<?php

session_start();

include "dbconnect.php";
include "functions.php";
include "header.php";

?>

<html>
    <head>
        <title>Kasutajate andmebaas</title>
    </head>
    <body bgcolor=AliceBlue text=DarkGoldenRod link=DarkSlateGray>
    </body>
    <h3>Kasutaja sisse logimine</h3>
<?php

echo "<form method=post action=".$_SERVER['SCRIPT_NAME'].">";
echo "Kasutajanimi: <input type=text name=entry1><br>";
echo "Parool: <input type=password name=entry2><br>";
echo "<input type=submit value=Login name=nupp>";
echo "</form>";

#login process

if (isset($_POST['nupp']))
{
  #against bruteforce
  sleep(1);
  
  $usr = str_secure($_POST['entry1']);
  $pwd = str_secure($_POST['entry2']);
  
  $query = "SELECT * FROM logimine WHERE username='$usr' AND password=PASSWORD('$pwd') LIMIT 1";
  $result = @mysql_query($query);
  $row = mysql_fetch_assoc($result);
  
  if #kui kõik sobib
  (isset($row['username']) AND $row['username'] != "" AND is_numeric($row['username']) != true AND $row['level'] > 0)
 
  {
    $queryok = "
    UPDATE logimine SET 
    logindate_ok=NOW(),
    logincount_ok=logincount_ok + 1,
    login_all=login_all + 1
    WHERE username='".$row['username']."'
    ";
    @mysql_query($queryok);
    
    echo "<span style='color: green'>Sisselogimine õnnestus.</span>";
    $_SESSION['login_user'] = $row;
    $_SESSION['login_user']['time'] = time ();
    echo '<META HTTP-EQUIV="Refres2h" CONTENT="0; URL=login.php">', "õige";
  }
  elseif #kui kasutajat pole
  (isset($row['username']) != true)
  { 
    $query_no_ok = " INSERT INTO logimine SET
    logindate_no_ok=NOW(),
    logincount_no_ok=logincount_no_ok + 1,
    login_all=login_all + 1,
    level=0,
    username='".$_POST['entry1']."'
    ";
    @mysql_query($query_no_ok)
  OR die ("Ebaõnnestus: " . mysql_error());
    
    echo "<span style='color: red'>Sisselogimine ebaõnnestus. Vale kasutajanimi ja/või parool.</span>",$_POST['entry1']," tundmatu";
  }
  else #vale password
  { 
    $query_no_pw = "
    UPDATE logimine SET 
    logindate_no_ok=NOW(),
    logincount_no_ok=logincount_no_ok + 1,
    login_all=login_all + 1
    WHERE username='".$row['username']."'
    ";
    @mysql_query($query_no_pw);

    echo "<span style='color: red'>Sisselogimine ebaõnnestus. Vale kasutajanimi ja/või parool.</span>"," Vale pass";
  }
}
include "footer.php";
?>